import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_base/src/config/color_util.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';

/// 图片查看器组件
/// 支持全屏查看、放大缩小，并提供可选的点击回调函数
class ImageViewer extends StatelessWidget {
  /// 图片URL
  final String imageUrl;

  /// 图片宽度
  final double? width;

  /// 图片高度
  final double? height;

  /// 图片填充方式
  final BoxFit fit;

  /// 边框圆角
  final double borderRadius;

  /// 点击回调函数
  final VoidCallback? onTap;

  /// 图片加载错误时的占位图
  final Widget? errorWidget;

  /// 图片加载中的占位图
  final Widget? loadingWidget;

  const ImageViewer({
    super.key,
    required this.imageUrl,
    this.width,
    this.height,
    this.fit = BoxFit.cover,
    this.borderRadius = 0,
    this.onTap,
    this.errorWidget,
    this.loadingWidget,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        if (onTap != null) {
          onTap!();
        } else {
          _showFullScreenImage(context);
        }
      },
      child: SizedBox(
        width: width,
        height: height,
        child: ClipRRect(
          borderRadius: BorderRadius.circular(borderRadius),
          child: CachedNetworkImage(
            imageUrl: imageUrl,
            fit: fit,
            fadeInDuration: const Duration(milliseconds: 100),
            errorWidget: (context, url, error) =>
                errorWidget ?? Image.asset("assets/images/default_image.png", width: width, height: height, fit: fit),
            placeholder: (context, url) =>
                loadingWidget ??
                Container(
                  color: ColorUtils.backgroundColor6,
                  child: const Center(child: CircularProgressIndicator(strokeWidth: 2)),
                ),
          ),
        ),
      ),
    );
  }

  /// 显示全屏图片
  void _showFullScreenImage(BuildContext context) {
    showDialog(
      context: context,
      useSafeArea: false,
      barrierColor: Colors.transparent,
      barrierDismissible: true,
      builder: (context) => _FullScreenImageViewer(imageUrl: imageUrl),
    );
  }
}

/// 全屏图片查看器
class _FullScreenImageViewer extends StatelessWidget {
  final String imageUrl;

  const _FullScreenImageViewer({required this.imageUrl});

  @override
  Widget build(BuildContext context) {
    return _DismissibleImageViewer(
      child: PhotoView(
        imageProvider: CachedNetworkImageProvider(imageUrl),
        initialScale: PhotoViewComputedScale.contained,
        minScale: PhotoViewComputedScale.contained * 0.8,
        maxScale: PhotoViewComputedScale.covered * 2.5,
        heroAttributes: PhotoViewHeroAttributes(tag: imageUrl),
        loadingBuilder: (context, event) => Center(
          child: SizedBox(
            width: 30,
            height: 30,
            child: CircularProgressIndicator(
              value: event == null ? 0 : event.cumulativeBytesLoaded / (event.expectedTotalBytes ?? 1),
            ),
          ),
        ),
        backgroundDecoration: const BoxDecoration(color: Colors.transparent),
        tightMode: true,
        gestureDetectorBehavior: HitTestBehavior.translucent,
      ),
    );
  }
}

/// 多图片查看器组件
/// 支持查看多张图片，全屏浏览、放大缩小
class MultiImageViewer extends StatefulWidget {
  /// 图片URL列表
  final List<String> imageUrls;

  /// 初始显示的图片索引
  final int initialIndex;

  const MultiImageViewer({super.key, required this.imageUrls, this.initialIndex = 0});

  /// 打开多图片查看器
  static void show(BuildContext context, {required List<String> imageUrls, int initialIndex = 0}) {
    showDialog(
      context: context,
      useSafeArea: false,
      barrierColor: Colors.transparent,
      barrierDismissible: true,
      builder: (context) => MultiImageViewer(imageUrls: imageUrls, initialIndex: initialIndex),
    );
  }

  @override
  State<MultiImageViewer> createState() => _MultiImageViewerState();
}

class _MultiImageViewerState extends State<MultiImageViewer> {
  late int _currentIndex;
  late PageController _pageController;

  // 缩放控制器
  final List<PhotoViewController> _controllers = [];

  // 双击检测器
  final List<PhotoViewScaleStateController> _scaleStateControllers = [];

  @override
  void initState() {
    super.initState();
    _currentIndex = widget.initialIndex;
    _pageController = PageController(initialPage: widget.initialIndex);

    // 为每个图片创建控制器
    for (int i = 0; i < widget.imageUrls.length; i++) {
      _controllers.add(PhotoViewController());
      _scaleStateControllers.add(PhotoViewScaleStateController());
    }
  }

  @override
  void dispose() {
    _pageController.dispose();
    for (final controller in _controllers) {
      controller.dispose();
    }
    for (final controller in _scaleStateControllers) {
      controller.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return _DismissibleImageViewer(
      child: Stack(
        children: [
          // 图片浏览区域
          PhotoViewGallery.builder(
            scrollPhysics: const BouncingScrollPhysics(),
            builder: (BuildContext context, int index) {
              return PhotoViewGalleryPageOptions(
                imageProvider: CachedNetworkImageProvider(widget.imageUrls[index]),
                initialScale: PhotoViewComputedScale.contained,
                minScale: PhotoViewComputedScale.contained * 0.8,
                maxScale: PhotoViewComputedScale.covered * 2.5,
                heroAttributes: PhotoViewHeroAttributes(tag: widget.imageUrls[index]),
                controller: _controllers[index],
                scaleStateController: _scaleStateControllers[index],
                scaleStateCycle: (state) {
                  // 双击时的缩放状态循环
                  switch (state) {
                    case PhotoViewScaleState.initial:
                      return PhotoViewScaleState.covering;
                    case PhotoViewScaleState.covering:
                      return PhotoViewScaleState.originalSize;
                    case PhotoViewScaleState.originalSize:
                      return PhotoViewScaleState.initial;
                    case PhotoViewScaleState.zoomedIn:
                    case PhotoViewScaleState.zoomedOut:
                      return PhotoViewScaleState.initial;
                  }
                },
                tightMode: true,
                gestureDetectorBehavior: HitTestBehavior.translucent,
              );
            },
            itemCount: widget.imageUrls.length,
            loadingBuilder: (context, event) => Center(
              child: SizedBox(
                width: 30,
                height: 30,
                child: CircularProgressIndicator(
                  value: event == null ? 0 : event.cumulativeBytesLoaded / (event.expectedTotalBytes ?? 1),
                ),
              ),
            ),
            backgroundDecoration: const BoxDecoration(color: Colors.transparent),
            pageController: _pageController,
            onPageChanged: (index) {
              setState(() {
                _currentIndex = index;
              });
            },
          ),

          // 底部指示器
          if (widget.imageUrls.length > 1)
            Positioned(
              bottom: 20,
              left: 0,
              right: 0,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: List.generate(
                  widget.imageUrls.length,
                  (index) => Container(
                    width: 8,
                    height: 8,
                    margin: const EdgeInsets.symmetric(horizontal: 4),
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: _currentIndex == index ? Colors.white : Colors.white.withOpacity(0.5),
                    ),
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }
}

/// 可下滑关闭的图片查看器
class _DismissibleImageViewer extends StatefulWidget {
  final Widget child;

  const _DismissibleImageViewer({required this.child});

  @override
  State<_DismissibleImageViewer> createState() => _DismissibleImageViewerState();
}

class _DismissibleImageViewerState extends State<_DismissibleImageViewer> {
  final double _dismissThreshold = 150.0; // 下滑多少距离后关闭
  double _dragDistance = 0.0; // 当前下滑距离
  bool _isDragging = false; // 是否正在拖拽

  @override
  Widget build(BuildContext context) {
    // 计算内容透明度
    final double contentOpacity = _dragDistance > 0
        ? 1 - (_dragDistance / (_dismissThreshold * 2)).clamp(0.0, 1.0)
        : 1.0;

    // 计算背景透明度 - 只有在拖拽时才变透明
    final double backgroundOpacity = _dragDistance > 0 ? 1 - (_dragDistance / _dismissThreshold).clamp(0.0, 1.0) : 1.0;

    // 计算缩放比例
    final double scale = _dragDistance > 0 ? 1 - (_dragDistance / (_dismissThreshold * 5)).clamp(0.0, 0.1) : 1.0;

    return WillPopScope(
      onWillPop: () async {
        // 拦截返回按钮，使用自定义动画关闭
        if (!_isDragging) {
          setState(() {
            _isDragging = true;
            _dragDistance = _dismissThreshold;
          });
          await Future.delayed(const Duration(milliseconds: 200));
        }
        return true;
      },
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        color: _isDragging ? Colors.black.withOpacity(backgroundOpacity) : Colors.black,
        child: GestureDetector(
          onTap: () => Navigator.of(context).pop(),
          onVerticalDragStart: (details) {
            setState(() {
              _isDragging = true;
              _dragDistance = 0;
            });
          },
          onVerticalDragUpdate: (details) {
            // 只处理向下拖拽
            if (details.delta.dy > 0) {
              setState(() {
                _dragDistance += details.delta.dy;
              });
            }
          },
          onVerticalDragEnd: (details) {
            if (_dragDistance >= _dismissThreshold) {
              // 达到关闭阈值，关闭查看器
              Navigator.of(context).pop();
            } else {
              // 未达到关闭阈值，恢复原状
              setState(() {
                _isDragging = false;
                _dragDistance = 0;
              });
            }
          },
          child: AnimatedContainer(
            duration: const Duration(milliseconds: 200),
            curve: Curves.easeOutCubic,
            transform: Matrix4.identity()
              ..translate(0.0, _dragDistance)
              ..scale(scale, scale),
            child: Opacity(opacity: contentOpacity, child: widget.child),
          ),
        ),
      ),
    );
  }
}
